package com.irdstudio.devops.console.api.rest;

import java.io.File;
import java.io.IOException;
import java.util.*;

import com.irdstudio.bfp.console.dao.domain.SubsCodeBase;
import com.irdstudio.devops.console.service.vo.FileCatalogVo;
import com.irdstudio.devops.console.util.MyRemoteShellClient;
import com.irdstudio.sdk.beans.ssh.utils.RemoteShellClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.*;
import com.irdstudio.devops.console.service.facade.SysDeployInfoService;
import com.irdstudio.devops.console.service.vo.SysDeployInfoVO;
import com.irdstudio.sdk.beans.core.vo.ResponseData;
import com.irdstudio.sdk.beans.web.controller.AbstractController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api")
@EnableAsync
public class SysDeployInfoController extends AbstractController  {
	
	@Autowired
	@Qualifier("sysDeployInfoServiceImpl")
	private SysDeployInfoService sysDeployInfoService;

	
	/**
	 * 列表数据查询
	 * @param
	 * @param
	 * @return
	 */
	@RequestMapping(value="/sys/deploy/infos", method=RequestMethod.POST)
	public @ResponseBody ResponseData<List<SysDeployInfoVO>> querySysDeployInfoAll(
			SysDeployInfoVO vo) {		
		List<SysDeployInfoVO> outputVo = sysDeployInfoService.queryAllOwner(vo);
		return getResponseData(outputVo);
		
	}
	
	/**
	 * 根据主键查询详情
	 * @return
	 */
	@RequestMapping(value="/sys/deploy/info/{appDeployId}", method=RequestMethod.GET)
	public @ResponseBody ResponseData<SysDeployInfoVO> queryByPk(@PathVariable("appDeployId") String appDeployId) {		
		SysDeployInfoVO inVo = new SysDeployInfoVO();
				inVo.setAppDeployId(appDeployId);
		SysDeployInfoVO outputVo = sysDeployInfoService.queryByPk(inVo);
		return getResponseData(outputVo);
		
	}
	
	/**
	 * 根据主键删除信息
	 * @param
	 * @return
	 */
	@RequestMapping(value="/sys/deploy/info", method=RequestMethod.DELETE)
	public @ResponseBody ResponseData<Integer> deleteByPk(@RequestBody SysDeployInfoVO inSysDeployInfoVo) {		
		int outputVo = sysDeployInfoService.deleteByPk(inSysDeployInfoVo);
		return getResponseData(outputVo);
		
	}
	
	/**
	 * 根据主键更新信息
	 * @param inSysDeployInfoVo
	 * @return
	 */
	@RequestMapping(value="/sys/deploy/info", method=RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateByPk(@RequestBody SysDeployInfoVO inSysDeployInfoVo) {

		int outputVo = sysDeployInfoService.updateByPk(inSysDeployInfoVo);

		return getResponseData(outputVo);
		
	}

	/**
	 * 更新subsCode
	 * @return
	 */
	@RequestMapping(value="/sys/deploy/info/change/subs/code", method=RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateBySubsCode(@RequestBody SubsCodeBase subsCodeBase) {
		int outputVo = sysDeployInfoService.updateBySubsCode(subsCodeBase);
		return getResponseData(outputVo);
	}

	/**
	 * 更新subsAppName
	 * @return
	 */
	@RequestMapping(value="/sys/deploy/info/change/app/name", method=RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateAppName(@RequestBody SysDeployInfoVO sysDeployInfoVO) {
		int outputVo = sysDeployInfoService.updateAppName(sysDeployInfoVO);
		return getResponseData(outputVo);
	}

	@RequestMapping(value = "/sys/deploy/info/upload")
	@ResponseBody
	public String upload(@RequestParam("file") MultipartFile file) {
		if (file.isEmpty()) {
			return "上传失败，文件为空，请选择文件";
		}
		String fileName = file.getOriginalFilename();
		String filePath = "/WarFile/";
		File dest = new File(filePath + fileName);
		try {
			file.transferTo(dest);
			return "上传成功";
		} catch (IOException e) {

		}
		return "上传失败！";
	}
	
	/**
	 * 新增数据
	 * @param inSysDeployInfoVo
	 * @return
	 */
	@RequestMapping(value="/sys/deploy/info", method=RequestMethod.POST)
	public @ResponseBody ResponseData<String> insertSysDeployInfo(@RequestBody SysDeployInfoVO inSysDeployInfoVo) {
		logger.debug("当前部署数据为:"+ inSysDeployInfoVo.toString());
		sysDeployInfoService.deploymentApplication(inSysDeployInfoVo);
		return getResponseData("正在部署");
	}

	/**
	 * 应用部署
	 */
	@RequestMapping(value="/sys/deploy/info/{appDeployId}/{type}", method=RequestMethod.GET)
	public @ResponseBody ResponseData<String> manualDeploymentRun(@PathVariable("appDeployId")  String appDeployId,@PathVariable("type") String type){
		SysDeployInfoVO inVo = new SysDeployInfoVO();
		inVo.setAppDeployId(appDeployId);
		SysDeployInfoVO sysDeployInfoVo = sysDeployInfoService.queryByPk(inVo);

		// 1.针对每台服务器应用
		logger.info("开始部署应用{}到服务器{},端口{}", sysDeployInfoVo.getAppName(),
				sysDeployInfoVo.getEcsName(), sysDeployInfoVo.getAppPort());
		// 远程操作Linux服务器
		MyRemoteShellClient rsc = new MyRemoteShellClient(sysDeployInfoVo.getEcsIp(),
				sysDeployInfoVo.getEcsLoginUser(), sysDeployInfoVo.getEcsLoginPwd());
		boolean loginFlag = rsc.login();
		if (!loginFlag) {
			logger.info("登陆服务器失败");
			return getResponseData("LoginFailure");
		}else {
			//查询应用文件地址是否存在
			boolean fileExists = rsc.getFileProperties2("/agent/"+sysDeployInfoVo.getAppName()+"/bin/");
			if (fileExists){
				logger.info("执行命令 " + "/agent/"+sysDeployInfoVo.getAppName()+"/bin/catalina.sh "+type);
				int status= rsc.exec("/agent/"+sysDeployInfoVo.getAppName()+"/bin/catalina.sh "+type);
				rsc.exit();
				if (status == -1){
					//执行失败
					return getResponseData("ExecFailure");
				}else {
					switch (type){
						case "start":
						case "restart":
							sysDeployInfoVo.setAppState("R");
							break;
						case "stop": sysDeployInfoVo.setAppState("S");
							break;
					}
					int outputVo = sysDeployInfoService.updateByPk(sysDeployInfoVo);
					//执行成功
					return getResponseData("Succeed");
				}
			}else {
				//应用路径不存在
				return getResponseData("AppNotExist");
			}
		}
	}

	/**
	 * 获取应用日志文件目录
	 */
	@RequestMapping(value = "/sys/deploy/info/get/files/{appDeployId}",method = RequestMethod.GET)
	public @ResponseBody ResponseData<FileCatalogVo> getApplicationLogFileDirectory(@PathVariable("appDeployId") String appDeployId){
		SysDeployInfoVO inVo = new SysDeployInfoVO();
		inVo.setAppDeployId(appDeployId);
		SysDeployInfoVO sysDeployInfoVo = sysDeployInfoService.queryByPk(inVo);

		MyRemoteShellClient rsc = new MyRemoteShellClient(sysDeployInfoVo.getEcsIp(),
				sysDeployInfoVo.getEcsLoginUser(), sysDeployInfoVo.getEcsLoginPwd());
		boolean loginFlag = rsc.login();
		ArrayList<String> files = rsc.getFileProperties(sysDeployInfoVo.getAppLogPath());
		// 进行升序排列
		files.sort(Comparator.naturalOrder());
		FileCatalogVo fileCatalogVo = new FileCatalogVo();
		fileCatalogVo.setFiles(files);
		return getResponseData(fileCatalogVo);
	}
	/**
	 * 获取log文件1000行内容
	 */
	@RequestMapping(value = "/sys/deploy/info/file/download/{appDeployId}/{fileName}/{last}/{isFirst}",method = RequestMethod.GET)
	public @ResponseBody ResponseData<Map<String,String>> logFileDownload (@PathVariable("appDeployId") String appDeployId,
																			@PathVariable("fileName") String fileName,
																			@PathVariable("last") int last,
																		   @PathVariable("isFirst") boolean isFirst){
		SysDeployInfoVO inVo = new SysDeployInfoVO();
		fileName = fileName.replaceAll("\\*",".");
		inVo.setAppDeployId(appDeployId);
		Map<String,String> stringIntegerMap = new HashMap<String,String>();
		SysDeployInfoVO sysDeployInfoVo = sysDeployInfoService.queryByPk(inVo);
		MyRemoteShellClient rsc = new MyRemoteShellClient(sysDeployInfoVo.getEcsIp(),
				sysDeployInfoVo.getEcsLoginUser(), sysDeployInfoVo.getEcsLoginPwd());
		boolean loginFlag = rsc.login();
		if (!loginFlag){
			return getResponseData(stringIntegerMap);
		}else {
			fileName = sysDeployInfoVo.getAppLogPath()+"/"+fileName;
			int head = last-1000;
			String file="";
			if (isFirst){
				String fileNumberRows =  rsc.execAndGetStdout("cat "+fileName+" | wc -l ");
				last = Integer.parseInt(fileNumberRows.trim());
				head = Integer.parseInt(fileNumberRows.trim())-1000;
				if (head<1){
					head =1;
				}
				file =  rsc.execAndGetStdout("sed -n '"+head+","+last+"p' "+fileName);
			}else {
				if (head<1){
					head =1;
				}
				last = last-1;
				file =  rsc.execAndGetStdout("sed -n '"+head+","+last+"p' "+fileName);
			}
			stringIntegerMap.put("file",file);
			stringIntegerMap.put("head",Integer.toString(head));
			return getResponseData(stringIntegerMap);
		}
	}


	/**
	 * 新增数据
	 * @param inSysDeployInfoVo
	 * @return
	 */
	@RequestMapping(value="/sys/deploy/info/local/log/file/{bpaSerialNo}", method=RequestMethod.GET)
	public @ResponseBody ResponseData<String> readLocalLogFile(@PathVariable("bpaSerialNo") String bpaSerialNo) {
		logger.debug("当前流水号为:"+ bpaSerialNo);
		String file = sysDeployInfoService.readLogFile(bpaSerialNo);
		return getResponseData(file);
	}




}
